package io.renren.modules.app.interceptor;

import cn.hutool.json.JSONUtil;
import io.renren.common.utils.CheckParam;
import io.renren.common.utils.RedisUtils;
import io.renren.modules.app.annotation.Delay;
import io.renren.modules.app.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class RequestFrequenceInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtils jwtUtils;

    @Resource
    private RedisUtils redisUtils;
//    private static Logger log = LoggerFactory.getLogger( RequestFrequenceInterceptor.class );
//    private long lastTime = 0;
    private boolean startDelay(int time,String key) {
        String value =redisUtils.get(key);
        if(CheckParam.isNull(value)){
            redisUtils.set(key, "1", time/1000);
            return true;
        }
//        long currentTime = System.currentTimeMillis();
//        if (currentTime - lastTime > time) {
//            System.out.println(currentTime + " - " + lastTime);
//            lastTime = currentTime;
//            return true;
//        }
        return false;
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获取用户凭证
        String token = request.getHeader(jwtUtils.getHeader());
        String path = request.getServletPath();
        if(StringUtils.isBlank(token)){
            token = request.getParameter(jwtUtils.getHeader());
        }
        if(StringUtils.isBlank(token)){
            token ="1";
        }
        String key = token + path;
        System.out.println(key);
        //开始进入请求地址拦截
        //获取执行方法上的注解  不过滤静态资源
        if(handler instanceof HandlerMethod){
            HandlerMethod hm = (HandlerMethod) handler;
            //对包含注解的方法进行频率验证
            Delay delay = hm.getMethodAnnotation(Delay.class);
            if (delay != null) {
                if ( startDelay(delay.time(),key))
                {
                    return true;
                }else {
                    log.warn( " 请求频率过快" );
                    Map<String,Object> responseMap = new HashMap<>();
                    responseMap.put( "code", "500" );
                    responseMap.put( "msg","请求被锁定,频率过快" );
                    String resStr = JSONUtil.toJsonStr(responseMap);
                    response.setContentType("application/json;charset=utf-8");
                    response.setHeader("Access-Control-Allow-Origin", "*");
                    response.setHeader("Cache-Control","no-cache");
                    response.getWriter().write(resStr);

                    return false;
                }
            }
        }



        //  对于不包含注解的方法一律放行
        return true;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        //处理请求完成后紧接着的操作
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        //视图渲染之后的操作
    }
}